<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import TnForm from '@tuniao/tnui-vue3-uniapp/components/form/src/form.vue'
import TnFormItem from '@tuniao/tnui-vue3-uniapp/components/form/src/form-item.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnImageUpload from '@tuniao/tnui-vue3-uniapp/components/image-upload/src/image-upload.vue'
import TnCheckbox from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox.vue'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import TnTag from '@tuniao/tnui-vue3-uniapp/components/tag/src/tag.vue'
import type {
  FormRules,
  TnFormInstance,
  ImageUploadCustomCallbackFunction,
} from '@tuniao/tnui-vue3-uniapp'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import PageContainer from '@/components/page-container/index'
import circles from '@/api/circles.js'
import circlesPost from '@/api/circlesPost.js'
import user from '@/api/user.js'
import {
  CHANNEL,
  FILE_URL,
  MP_API_URL,
  USER_INFO,
  USER_TOKEN,
} from '@/api/config'

// 导航栏的高度
const navbarHeight = ref(0)
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}
const formRef = ref<TnFormInstance>()
const state = reactive({
  loading: false,
  userToken: '',
  formData: {
    attachment_type: 'none',
    attachment: '',
    circles_id: 0,
    circles_zone_id: 0,
    content: '',
    money: '',
    location: '',
    poiaddress: '',
    longitude: '',
    latitude: '',
    sync_homepage: 0,
    channel: '',
  },
  imageList: [],
  fullImageList: [],
  showCirclesPopup: false,
  circlesName: '请选择圈子与分区',
  circlesList: [],
  currentTagIndex: -1,
  tagsData: [],
  userInfo: {},
})
const changeSyncHomepage = () => {
  if (!state.userInfo.is_vip || state.userInfo.is_vip == 0) {
    uni.showToast({
      title: '非会员不可同步！',
      duration: 3000,
      icon: 'none',
    })
    state.formData.sync_homepage = 0
  }
}
const uploadCallbackHandle: ImageUploadCustomCallbackFunction = (
  data: UniApp.UploadFileSuccessCallbackResult
) => {
  const resData = JSON.parse(data.data)
  console.log(resData, 'images')
  if (resData.code == 1) {
    state.formData.attachment_type = 'image'
    state.imageList.push(resData.data.file.url)
    state.formData.attachment = state.imageList.join(',')
    console.log(state.formData.attachment, 'images2')
    return FILE_URL + resData.data.file.url
  }
}
const changeImageList = (images: any) => {
  console.log('changeImage', images)
  if (images.length == 0) {
    state.formData.attachment_type = 'none'
    state.formData.attachment = ''
  }
}

const userCirclesZone = () => {
  circles
    .userCirclesZone({
      plate: 'organizeBureau',
    })
    .then((res) => {
      if (res.code == 1) {
        console.log(res.data, 'userCirclesZone')
        state.circlesList = res.data
      }
    })
    .catch((err) => {
      console.log(err, 'userCirclesZone')
    })
}

const getCirclesPlateZone = (circlesId: number, circlesPlate: string) => {
  circles
    .circlesPlateZone({
      plate: circlesPlate,
      circles_id: circlesId,
    })
    .then((res) => {
      if (res.code == 1) {
        console.log(res.data, 'getCirclesPlateZone')
        state.tagsData = res.data
      }
    })
    .catch((err) => {
      console.log(err, 'getCirclesPlateZone')
    })
}

// 点击分区标签
const handleTagClick = (index: number, circlesZoneId: number) => {
  state.currentTagIndex = index
  state.formData.circles_zone_id = circlesZoneId
}

const clickSelectCircles = (
  circlesId: number,
  circlesName: string,
  circlesZone: any
) => {
  state.currentTagIndex = -1
  state.circlesName = circlesName
  state.formData.circles_id = circlesId
  state.tagsData = circlesZone
  state.showCirclesPopup = false
}

// 打开地图选择位置
const clickChooseLocation = () => {
  uni.chooseLocation({
    success: function (res) {
      state.formData.location = res.name
      state.formData.poiaddress = res.address
      state.formData.longitude = res.longitude
      state.formData.latitude = res.latitude
    },
  })
}

const clickCircles = () => {
  state.showCirclesPopup = true
  userCirclesZone()
}

// 规则
const formRules: FormRules = {
  content: [
    { required: true, message: '请输入内容', trigger: ['change', 'blur'] },
    {
      min: 5,
      max: 1000,
      message: '长度在 5 到 1000 个字符',
      trigger: 'blur',
    },
  ],
}
const submitForm = () => {
  state.loading = true
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      circlesPost
        .publishUsedIdle(state.formData)
        .then((res) => {
          console.log(res, 'publishUsedIdle')
          state.loading = false
          if (res.code == 1) {
            uni.showToast({
              title: '提交成功',
            })
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              })
            }, 2000)

            updateUserLevel()
          } else {
            state.loading = false
            uni.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          console.log(err, 'publishUsedIdle')
        })
    } else {
      uni.showToast({
        title: '表单校验失败',
        icon: 'none',
      })
    }
  })
}
const updateUserLevel = () => {
  user
    .updateUserLevel({
      type: 'publishUsedIdle',
    })
    .then((res) => {})
}
onMounted(() => {
  state.userToken = uni.getStorageSync(USER_TOKEN)
  state.formData.channel = uni.getStorageSync(CHANNEL)

  const userInfo = uni.getStorageSync(USER_INFO)
  if (userInfo) {
    state.userInfo = userInfo
  }
})
onLoad((options) => {
  console.log(options, 'options')
  state.formData.circles_id = options.circlesId
  state.circlesName = options.name
  getCirclesPlateZone(options.circlesId, options.plate)
})
</script>
<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      frosted
      :placeholder="false"
      :bottom-shadow="false"
      :z-index="999"
      @init-finish="navbarInitFinishHandle"
    >
      发布闲置
    </TnNavbar>

    <view
      class="form-container"
      :style="{ paddingTop: `${navbarHeight + 10}px` }"
    >
      <TnForm
        ref="formRef"
        :model="state.formData"
        :rules="formRules"
        label-width="150"
        label-position="top"
      >
        <TnFormItem prop="content">
          <TnInput
            v-model="state.formData.content"
            type="textarea"
            height="200"
            :border="false"
            :maxlength="1000"
            confirm-type="done"
            placeholder="描述一下宝贝的品牌型号、货品信息...（5-1000个字）"
          />
        </TnFormItem>
        <TnFormItem>
          <TnImageUpload
            v-model="state.fullImageList"
            :limit="9"
            :action="MP_API_URL + '/system.System/upload'"
            :header="{
              Authorization: state.userToken,
            }"
            :custom-upload-callback="uploadCallbackHandle"
            @change="changeImageList"
          />
        </TnFormItem>
        <TnFormItem>
          <TnButton
            plain
            shape="round"
            border-color="tn-grey-disabled"
            :custom-style="{
              padding: '5rpx 15rpx 5rpx 10rpx',
            }"
            @click="clickChooseLocation"
          >
            <TnIcon name="location-fill" size="35" color="tn-blue" />
            <view
              v-if="state.formData.location == ''"
              class="location-name tn-text-ellipsis-1 tn-text-xs"
              >添加地点</view
            >
            <view v-else class="location-name tn-text-ellipsis-1 tn-text-xs">{{
              state.formData.location
            }}</view>
          </TnButton>
        </TnFormItem>
        <view class="tn-border tn-gray-light_border" style="margin: 14rpx 0" />

        <view class="form">
          <view class="form-item">
            <view class="title"> 商品价格 </view>
            <view class="content">
              <TnInput
                v-model="state.formData.money"
                type="number"
                :border="false"
                right-icon="right"
                text-align="right"
                placeholder="请输入商品价格"
              />
            </view>
          </view>
        </view>

        <view class="form">
          <view class="form-item">
            <view class="title">
              <TnIcon name="circle-more" />
              圈子与分区
            </view>
            <view class="content" @click="clickCircles">
              <TnInput
                v-model="state.formData.circles_type"
                :disabled="true"
                :border="false"
                confirm-type="done"
                right-icon="right"
                text-align="right"
                :placeholder="state.circlesName"
                :custom-style="{
                  backgroundColor: 'transparent',
                }"
              />
            </view>
          </view>
          <TnTag
            v-for="(item, index) in state.tagsData"
            :key="index"
            shape="round"
            bg-color="#f8f7f8"
            :border="false"
            :border-color="
              state.currentTagIndex == index ? '#01beff' : '#ebebeb'
            "
            :text-color="state.currentTagIndex == index ? '#01beff' : '#7d7d7d'"
            :custom-style="{
              borderRadius: '6rpx',
              padding: '8rpx 10rpx',
              marginBottom: '20rpx',
              marginRight: '20rpx',
              fontSize: '24rpx',
            }"
            custom-class="zone-item tn-flex-center tn-flex-column"
            @click="handleTagClick(index, item.id)"
          >
            {{ item.name }}
          </TnTag>
        </view>
        <TnFormItem>
          <TnCheckbox
            v-model="state.formData.sync_homepage"
            checked-shape="circle"
            :custom-style="{
              padding: '30rpx 20rpx',
              backgroundColor: '#f8f7f8',
              borderRadius: '50rpx',
              height: '30rpx',
              width: '220rpx',
              overflow: 'hidden',
              fontSize: '25rpx',
              marginTop: '30rpx',
            }"
            @change="changeSyncHomepage"
          >
            同步到首页
          </TnCheckbox>
        </TnFormItem>
      </TnForm>
    </view>

    <!-- 底部悬浮按钮 -->
    <view class="tn-footerfixed">
      <view class="publish-button">
        <TnButton
          v-if="state.formData.content == ''"
          width="80%"
          height="80rpx"
          type="primary"
          :disabled="true"
          shape="round"
          :shadow="true"
          :bold="true"
          :custom-style="{
            margin: '30rpx auto',
            fontSize: '34rpx',
          }"
          >发 布</TnButton
        >
        <TnButton
          v-else
          width="80%"
          height="80rpx"
          type="primary"
          shape="round"
          :shadow="true"
          :bold="true"
          :custom-style="{
            margin: '30rpx auto',
            fontSize: '34rpx',
          }"
          :debounce="true"
          @click="submitForm"
          >发 布</TnButton
        >
      </view>
    </view>

    <!-- 选择圈子 只能选择已关注的圈子 -->
    <TnPopup
      v-model="state.showCirclesPopup"
      :close-btn="true"
      open-direction="bottom"
      width="100%"
      height="90%"
    >
      <view class="tn-text-center tn-mt tn-text-xl"> 我关注的圈子 </view>
      <view class="circles">
        <view class="circles-list">
          <view
            v-for="(item, index) in state.circlesList"
            :key="index"
            class="list-item tn-shadow"
          >
            <view
              class="list-info"
              @click="clickSelectCircles(item.id, item.name, item.circlesZone)"
            >
              <view class="image">
                <image
                  class="tn-image"
                  :src="FILE_URL + item.image"
                  mode="aspectFill"
                />
              </view>
              <view class="title-desc">
                <view class="title tn-text-ellipsis-1">{{ item.name }}</view>
                <view class="item-desc tn-text-ellipsis-1">{{
                  item.introduce
                }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </TnPopup>
  </PageContainer>
</template>

<style lang="scss" scoped>
@use '../styles/publish/usedIdle.scss';
</style>
